import axios from 'axios';
import { showToast } from 'vant';
import router from '@/router';
import qs from 'qs'; // 需要安装 qs 包

// 创建需要 form-urlencoded 的接口列表
const formUrlencodedApis = [
  '/auth/login',
  '/auth/register',
  '/cars',
  '/cars/',  // 用于匹配 /cars/:id
  '/auth/sendVerifyCode'
];

const request = axios.create({
  baseURL: 'http://127.0.0.1:3000/api/v1',
  timeout: 10000,
});

// 判断是否需要 form-urlencoded
const needFormUrlencoded = (url) => {
  return formUrlencodedApis.some(api => url.includes(api));
};

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    console.log('请求拦截器:', config.url, config.params); // 添加日志

    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    // 处理 form-urlencoded 请求
    if (needFormUrlencoded(config.url)) {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
      if (config.method === 'post') {
        config.data = qs.stringify(config.data);
      }
    }

    // 处理文件上传
    if (config.url.includes('/user/auth')) {
      config.headers['Content-Type'] = 'multipart/form-data';
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const { data } = response;
    if (data.success) {
      return data.data;
    } else {
      showToast(data.message || '请求失败');
      return Promise.reject(new Error(data.message || '请求失败'));
    }
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // token 过期或无效
          localStorage.removeItem('token');
          router.push('/login');
          break;
        case 403:
          showToast('没有权限');
          break;
        case 404:
          showToast('请求的资源不存在');
          break;
        case 500:
          showToast('服务器错误');
          break;
        default:
          showToast('网络错误');
      }
    } else {
      showToast('网络连接失败');
    }
    return Promise.reject(error);
  }
);

export default request; 